package com.ruoyi.ma.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.ma.domain.MaMaterialMeasureSingle;
import com.ruoyi.ma.domain.MaMaterialSupplier;
import com.ruoyi.ma.domain.MaReportFormPayment;
import com.ruoyi.ma.mapper.MaMaterialSupplierMapper;
import com.ruoyi.ma.mapper.MaReportFormPaymentMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.ma.domain.bo.MaMaterialMeasureQhBo;
import com.ruoyi.ma.domain.vo.MaMaterialMeasureQhVo;
import com.ruoyi.ma.domain.MaMaterialMeasureQh;
import com.ruoyi.ma.mapper.MaMaterialMeasureQhMapper;
import com.ruoyi.ma.service.IMaMaterialMeasureQhService;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 材料计量期号Service业务层处理
 *
 * @author llb
 * @date 2024-11-01
 */
@RequiredArgsConstructor
@Service
public class MaMaterialMeasureQhServiceImpl implements IMaMaterialMeasureQhService {

    private final MaMaterialMeasureQhMapper baseMapper;
    private final MaMaterialSupplierMapper supplierMapper;
    private final MaReportFormPaymentMapper paymentMapper;

    /**
     * 查询材料计量期号
     */
    @Override
    public MaMaterialMeasureQhVo queryById(Long measureQhId){
        return baseMapper.selectVoById(measureQhId);
    }

    /**
     * 查询材料计量期号列表
     */
    @Override
    public TableDataInfo<MaMaterialMeasureQhVo> queryPageList(MaMaterialMeasureQhBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MaMaterialMeasureQh> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(MaMaterialMeasureQh::getQh);
        Page<MaMaterialMeasureQhVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询材料计量期号列表
     */
    @Override
    public List<MaMaterialMeasureQhVo> queryList(MaMaterialMeasureQhBo bo) {
        LambdaQueryWrapper<MaMaterialMeasureQh> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(MaMaterialMeasureQh::getQh);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MaMaterialMeasureQh> buildQueryWrapper(MaMaterialMeasureQhBo bo){
        // 日期处理
        Date beginDate = null;
        Date endDate = null;
        Date chargebacksEndDate = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (StringUtils.isNotBlank(bo.getBeginDate())) {
                beginDate = sdf.parse(bo.getBeginDate());
            }
            if (StringUtils.isNotBlank(bo.getEndDate())) {
                endDate = sdf.parse(bo.getEndDate());
            }
            if (StringUtils.isNotBlank(bo.getChargebacksEndDate())) {
                chargebacksEndDate = sdf.parse(bo.getChargebacksEndDate());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MaMaterialMeasureQh> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getBdId() != null, MaMaterialMeasureQh::getBdId, bo.getBdId());
        lqw.eq(bo.getZdId() != null, MaMaterialMeasureQh::getZdId, bo.getZdId());
        lqw.eq(bo.getGysId() != null, MaMaterialMeasureQh::getGysId, bo.getGysId());
        lqw.eq(bo.getType() != null, MaMaterialMeasureQh::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getCurrentQhFlag()), MaMaterialMeasureQh::getCurrentQhFlag, bo.getCurrentQhFlag());
        lqw.eq(bo.getQh() != null, MaMaterialMeasureQh::getQh, bo.getQh());
        lqw.like(StringUtils.isNotBlank(bo.getQhName()), MaMaterialMeasureQh::getQhName, bo.getQhName());
        lqw.like(beginDate != null, MaMaterialMeasureQh::getBeginDate, beginDate);
        lqw.like(endDate != null, MaMaterialMeasureQh::getEndDate, endDate);
        lqw.like(chargebacksEndDate != null, MaMaterialMeasureQh::getChargebacksEndDate, chargebacksEndDate);
        return lqw;
    }

    /**
     * 新增材料计量期号
     */
    @Override
    @Transactional
    public Boolean insertByBo(MaMaterialMeasureQhBo bo) {
        // 获取供应商信息
        LambdaQueryWrapper<MaMaterialSupplier> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getGysId() != null, MaMaterialSupplier::getSupplierId, bo.getGysId());
        MaMaterialSupplier supplier = supplierMapper.selectById(bo.getGysId());
        bo.setBdId(supplier.getBdId());
        bo.setZdId(supplier.getZdId());
        bo.setGysId(supplier.getSupplierId());
        // 判断是否当前期数
        isCurrent(bo.getGysId(), bo.getCurrentQhFlag());
        // 新增
        MaMaterialMeasureQh add = BeanUtil.toBean(bo, MaMaterialMeasureQh.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setMeasureQhId(add.getMeasureQhId());
        }
        // 同步新增支付报表
        MaReportFormPayment report = BeanUtil.toBean(add, MaReportFormPayment.class);
        report.setWorkflowsStateus("00");
        paymentMapper.insert(report);
        return flag;
    }

    /**
     * 判断是否当前期数,是则修改同一供应商下其他数据未非默认期数
     * @param gysId
     * @param currentQhFlag
     */
    @Transactional
    public void isCurrent(Long gysId, String currentQhFlag) {
        if ("1".equals(currentQhFlag)) {
            LambdaQueryWrapper<MaMaterialMeasureQh> lqw = Wrappers.lambdaQuery();
            lqw.eq(gysId != null, MaMaterialMeasureQh::getGysId, gysId);
            List<MaMaterialMeasureQh> list = baseMapper.selectList(lqw);
            list.forEach(item -> {
                item.setCurrentQhFlag("0");
            });
            baseMapper.updateBatchById(list);
        }
    }

    /**
     * 修改材料计量期号
     */
    @Override
    public Boolean updateByBo(MaMaterialMeasureQhBo bo) {
        isCurrent(bo.getGysId(), bo.getCurrentQhFlag());
        MaMaterialMeasureQh update = BeanUtil.toBean(bo, MaMaterialMeasureQh.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MaMaterialMeasureQh entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除材料计量期号
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 查询材料计量期号列表不分页
     *
     * @param bo
     * @return
     */
    @Override
    public List<MaMaterialMeasureQhVo> allList(MaMaterialMeasureQhBo bo) {
        LambdaQueryWrapper<MaMaterialMeasureQh> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(MaMaterialMeasureQh::getQh);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 获取最新期号
     *
     * @param bo
     * @return
     */
    @Override
    public Integer lastQh(MaMaterialMeasureQhBo bo) {
        LambdaQueryWrapper<MaMaterialMeasureQh> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getGysId() != null, MaMaterialMeasureQh::getGysId, bo.getGysId());
        lqw.select(MaMaterialMeasureQh::getQh);
        lqw.orderByDesc(MaMaterialMeasureQh::getQh);
        lqw.last("limit 1");
        List<MaMaterialMeasureQh> list = baseMapper.selectList(lqw);
        Integer qh = list.isEmpty() ? 0 : (Integer) list.get(0).getQh();
        return qh + 1;
    }
}
